package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.item.vo.CategoryView;
import com.atguigu.gmall.product.entity.BaseCategory1;
import com.atguigu.gmall.product.mapper.BaseCategory1Mapper;
import com.atguigu.gmall.product.service.BaseCategory1Service;
import com.atguigu.gmall.weball.vo.CategoryVo;
import com.atguigu.mall.cache.annotation.MallCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class BaseCategory1ServiceImpl extends ServiceImpl<BaseCategory1Mapper,BaseCategory1> implements BaseCategory1Service {
    @Autowired
    BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    public List<CategoryVo> getCategoryTreeDataWithCache() {
        String categorys = redisTemplate.opsForValue().get("categorys");
        if (!StringUtils.isEmpty(categorys)){
            //缓存命中
            List<CategoryVo> list = JSON.parseObject(categorys, new TypeReference<List<CategoryVo>>() {
            });
            return list;
        }
        //回源 未命中
        List<CategoryVo> vos = baseCategory1Mapper.getCategoryTreeData();

        redisTemplate.opsForValue().set("categorys",JSON.toJSONString(vos));
        return vos;
    }

    //本地缓存
    Map<String,List<CategoryVo>> cache = new ConcurrentHashMap<>();

    public List<CategoryVo> getCategoryTreeDataWithLocalCache() {

        //先查缓存
        List<CategoryVo> categorys = cache.get("categorys");
        if (categorys!=null){
            //缓存命中，直接返回
            return categorys;
        }

        //缓存未命中,查询数据库 【回源】
        List<CategoryVo> data = baseCategory1Mapper.getCategoryTreeData();
        //把数据放到缓存 方便下一个人使用
        cache.put("categorys",data);

        return data;
    }


    @MallCache(cacheKey = RedisConst.CATEGORY_CACHE_KEY)
    @Override
    public List<CategoryVo> getCategoryTreeData() {
        return baseCategory1Mapper.getCategoryTreeData();
    }

    @Override
    public CategoryView getSkuCategoryView(Long c3Id) {

        return baseCategory1Mapper.getSkuCategoryView(c3Id);
    }
}
